package com.killer.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 定义登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 会在handler方法业务逻辑执行之前执行⾏
     * 往往在这⾥完成权限校验⼯作
     * @param request
     * @param response
     * @param handler
     * @return  返回值boolean代表是否放行，true代表放行，false代表不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();
        //这里为了简化，就不将他放在token里解析(正常应该这样做的),也不做用户的区分
        Object data = session.getAttribute("login");
        if (data != null) {
            //data!=null就代表登录了（data随便一个值，简化)
            return true;
        }
        response.getWriter().write("{code:401}");
        return false;
    }
    /**
     * 会在handler方法业务逻辑执行之后尚未跳转页面时执⾏
     * @param request
     * @param response
     * @param handler
     * @param modelAndView  封装了视图和数据，此时尚未跳转页面呢，你可以在这里针对返回的
    数据和视图信息进行修改
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    /**
     * 页面已经跳转渲染完毕之后执⾏
     * @param request
     * @param response
     * @param handler
     * @param ex  可以在这⾥捕获异常
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
